import * as THREE from "../../../../../modules/three/three.module.js";
import { flatten } from '../../util/StaticMethods.js';
import {LineBasicMaterial} from "../../../../../modules/three/three.module.js";

/**
 * 创建箭头mesh
 */
export default class AxisArrow extends THREE.Object3D {
  constructor(color, arrowLen = 0.2, offsetToBottom = false) {
    super();
    this.color = color;
    const a = arrowLen; // 正三角形的边长
    const b = a * 1.0; // 箭头的矩形部分的长度
    const sqrt3 = Math.sqrt(3);
    const p0_y = (0.5 * sqrt3 * a + b) * 0.5;
    const p0 = new THREE.Vector3(0, p0_y, 0);
    const p1 = new THREE.Vector3(-0.5 * a, 0.5 * b - 0.25 * sqrt3 * a, 0);
    const p2 = new THREE.Vector3(-0.25 * a, p1.y, 0);
    const p3 = new THREE.Vector3(-0.25 * a, -p0.y, 0);
    const p4 = new THREE.Vector3(0.25 * a, -p0.y, 0);
    const p5 = new THREE.Vector3(0.25 * a, p1.y, 0);
    const p6 = new THREE.Vector3(0.5 * a, p1.y, 0);
    const arr = [p0, p1, p2, p3, p4, p5, p6];
    if (offsetToBottom) {
      // 使箭头中心点偏移到箭头底部
      arr.forEach((vector) => (vector.y += p0_y));
    }
    const geometry = new THREE.BufferGeometry();
    const posAttr = new THREE.BufferAttribute(flatten(arr), 3);
    geometry.setAttribute('position', posAttr);
    geometry.setIndex([0, 1, 6, 2, 3, 4, 2, 4, 5]);
    const mat = new THREE.MeshBasicMaterial({
      color: color,
      transparent: true,
      opacity: 0.5,
      depthTest: false,
      side: THREE.DoubleSide,
      toneMapped: false,
    });
    const mesh = new THREE.Mesh(geometry, mat);
    mesh.renderOrder = 7;
    this.add(mesh);

    const lineGeo = new THREE.BufferGeometry()
    lineGeo.setAttribute('position', posAttr);
    lineGeo.setIndex([0,1, 1,2, 2,3, 3,4, 4,5, 5,6, 6,0]);
    const contour = new THREE.LineSegments(lineGeo, new LineBasicMaterial({color}))
    mesh.add(contour)
  }
}
